<?php

namespace app\admin\controller\speech;

use app\common\controller\Backend;
use think\Db;
use think\Request;
/**
 * 关键词
 *
 * @icon fa fa-circle-o
 */
class Faq extends Backend
{

    /**
     * SpeechFaq模型对象
     * @var \app\admin\model\SpeechFaq
     */
    protected $model = null;
    protected $dataLimit = 'auth';
    protected $searchFields = 'id,keyword,speech_id';
    protected $noNeedRight = ['important'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('SpeechFaq');
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function keyword($tts=null)
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
//                var_dump($status);
                return $this->selectpage($tts);
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->with('admin')
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with('admin')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->getRelation('admin')->visible(['nickname']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    public function important($id,$important)
    {
        if($this->request->isAjax()){
            echo Db::name('speech_faq')->where('id',$id)->update(['important'=>$important]);
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        $speech_id = $this->request->get('speech_id');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['speech_id']=$speech_id;
                    $params['keyword']=str_replace("，",",",$params['keyword']);
//                    var_dump($params);
//                    $keywords=explode(',',str_replace("，",",",$params['keyword']));
//                    foreach ($keywords as $keyword){
//
//                        $this->model->whereExists()
//                        $result = $this->model->allowField(true)->save($params);
//                    }
                    $check = Db::name('speech_faq')
                        ->where('speech_id',$params['speech_id'])
                        ->where('keyword',$params['keyword'])
                        ->count();
                    if($check >=3)
                    {
                        $this->error('最多只能添加三条');
                    }

                    $result = $this->model->allowField(true)->save($params);

                    $check +=1;


                    if( !$this->request->post('sound_id2')&&$this->request->post('no_sound_id2'))
                    {
                        $this->error('请选择引导语音');
                    }

                    if($this->request->post('sound_id2'))
                    {
                        if($check >=3)
                        {
                            $this->error('最多只能添加三条');
                        }

                        Db::name('speech_faq')
                            ->insert([
                                'keyword' => $params['keyword'],
                                'speech_id' => $params['speech_id'],
                                'sound_id'  => $this->request->post('sound_id2'),
                                'no_sound_id'=>$this->request->post('no_sound_id2')?:0,
                                'admin_id'  => $this->auth->id,
                            ]);
                        $check +=1;
                    }

                    if( !$this->request->post('sound_id3')&&$this->request->post('no_sound_id3'))
                    {
                        $this->error('请选择引导语音');
                    }
                    if($this->request->post('sound_id3'))
                    {
                        if($check >=3)
                        {
                            $this->error('最多只能添加三条');
                        }

                        Db::name('speech_faq')
                            ->insert([
                                'keyword' => $params['keyword'],
                                'speech_id' => $params['speech_id'],
                                'sound_id'  => $this->request->post('sound_id3'),
                                'no_sound_id'=>$this->request->post('no_sound_id3')?:0,
                                'admin_id'  => $this->auth->id,
                            ]);

                    }

                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    public function edit($ids = NULL)
    {

        $row = $this->model->get($ids);
        $speechId = Db::name('speech_faq')
            ->where('id',$ids)
            ->value('speech_id');
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    $result = $row->allowField(true)->save($params);


                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign('faq_id', $ids);
        $this->view->assign('speech_id', $speechId);
        return $this->view->fetch();
    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $speech_id = $this->request->get('speech_id');
        $router=new Router();
//        $router->json_speech1($speech_id);
        $router->asyn_json(Request::instance()->domain(),$this->request->get('speech_id'));

        $where2['speech_id'] = ['=', $speech_id];
//        var_dump($speech_id);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['sound'])
                ->where($where)
                ->where($where2)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['sound'])
                ->where($where)
                ->where($where2)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
//            var_dump($where2);
            foreach ($list as $row) {
                $row['speech_name'] = Db::name('speech')->where('id', $row["speech_id"])->value('name');
                $row->getRelation('sound')->visible(['name', 'type', 'file', 'file_size']);
                $row['no_sound']=Db::name('sound')->where('id',$row['no_sound_id'])->find();
            }
            $list = collection($list)->toArray();
            $speechId = isset($list[0]['speech_id'])?$list[0]['speech_id']:'';

            foreach ($list as &$value)
            {

                $num = Db::name('speech_faq')
                    ->where('keyword',$value['keyword'])
                    ->where('sound_id','<>','')
                   // ->where('admin_id',$this->auth->id)
                    ->where('speech_id',$speechId)
                    ->count();

                $noNum = Db::name('speech_faq')
                    ->where('keyword',$value['keyword'])
                    ->where('no_sound_id','<>','')
                   // ->where('admin_id',$this->auth->id)
                    ->where('speech_id',$speechId)
                    ->count();

                $value['num'] = $num;
                $value['no_num'] = $noNum;
            }

            $out = [];
            $arr = [];

            foreach ($list as $key=>&$value) {

                if (!in_array($value['keyword'], $out))
                {
                    $out[$key] = $value['keyword'];
                    $arr[] = $value;
                }
            }

            $result = array("total" => $total, "rows" => $arr);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑改写
     */
    public function modify()
    {
        $array      =json_decode($_POST['array']);

        $name       = $this->request->post('name');
        $speechId   = $this->request->post('speech_id');

        if(!$array)
        {
            $this->error('参数错误');
        }

        $arr = [];
        foreach ($array as $value)
        {
            $arr[] = (array)$value;
        }

        foreach ($arr as $val)
        {
            if(!isset($val['sound_id']))
            {
                $this->error('请选择引导语音');
            }
        }

        foreach ($arr as $value){

            if(isset($value['id']))
            {
                Db::name('speech_faq')
                    ->where('id',$value['id'])
                    ->update([
                        'keyword'		=> $name,
			'sound_id'      => $value['sound_id'],
                        'no_sound_id'   => isset($value['no_sound_id'])?$value['no_sound_id']:'',
                        'important'     => $this->request->post('important'),
                    ]);
            }else{
                Db::name('speech_faq')
                    ->insert([
                        'keyword' => $name,
                        'speech_id' => $speechId,
                        'sound_id'  => $value['sound_id'],
                        'no_sound_id'=>isset($value['no_sound_id'])?$value['no_sound_id']:'',
                        'admin_id'  => $this->auth->id,
                        'important' => 1,
                    ]);
            }
        }


        $this->success();
    }


    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 话术页面的下拉展开
     */
    public function detail()
    {
        $speechId = $this->request->get('speech_id');
        $faqId = $this->request->get('faq_id');
        if (!$faqId) {
            $this->error('参数错误');
        }
        $faqInfo = Db::name('speech_faq')
            ->where('id', $faqId)
            ->find();

        if (!$faqInfo) {
            $this->error('系统错误');
        }
        $data = Db::name('sound')
            ->alias('s')
            ->join('speech_faq r','s.id = r.sound_id','left')
            ->where('r.keyword',$faqInfo['keyword'])
         //   ->where('r.admin_id',$this->auth->id)
            ->where('r.speech_id',$speechId)
            ->field('r.id,r.keyword as name,r.sound_id,s.name as file_name,s.file')
            ->select();

        $data1 = Db::name('sound')
            ->alias('s')
            ->join('speech_faq r','s.id =r.no_sound_id','left')
            ->where('r.keyword',$faqInfo['keyword'])
         //   ->where('r.admin_id',$this->auth->id)
            ->where('r.speech_id',$speechId)
            ->field('r.id,r.keyword as no_name,r.no_sound_id as sound_id,s.name as file_name,s.file')
            ->select();

        $router = array_merge($data,$data1);

        $arr = [];

        foreach ($router as $value)
        {
            $arr[$value['id']]['id'] = $value['id'];

            if(isset($value['name']))
            {
                $arr[$value['id']]['name'] = $value['name'];
                $arr[$value['id']]['file'] = $value['file'];
                $arr[$value['id']]['sound_id'] = $value['sound_id'];
                $arr[$value['id']]['file_name'] = $value['file_name'];

            }
            if(isset($value['no_name']))
            {
                $arr[$value['id']]['no_name'] = $value['no_name'];
                $arr[$value['id']]['no_file'] = $value['file'];
                $arr[$value['id']]['no_sound_id'] = $value['sound_id'];
                $arr[$value['id']]['no_file_name'] = $value['file_name'];
            }
        }

        $arr = array_values($arr);

        return json($arr);
    }

    public function line_edit()
    {
        $oldName = $this->request->post('old_name');
        $name = $this->request->post('name');
        $speechId = $this->request->post('speech_id');

        if(!$name || !$oldName || !$speechId)
        {
            $this->error('参数错误');
        }

        Db::name('speech_faq')
            ->where('keyword',$oldName)
            ->where('admin_id',$this->auth->id)
            ->where('speech_id',$speechId)
            ->update(['keyword'=>$name]);
        $this->success();
    }


    /**
     * 全面删除
     */
    public function drop()
    {
        $speechId = $this->request->post('speech_id');
        $name     = $this->request->post('name');

        if(!$speechId || !$name)
        {
            $this->error('参数错误');
        }
        $data = Db::name('speech_faq')
            ->where('speech_id',$speechId)
            ->where('keyword',$name)
            ->where('admin_id',$this->auth->id)
            ->delete();

        $this->success();
    }

}
